// me.js
const regeneratorRuntime = require('../../lib/runtime');
const Api = require('../../utils/api.js');
const wx = require('../../lib/wx');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    carNum:0,
    orderInfo: [{
      color: '',
      size: '',
      productNum: '1',
      price: '00.00',
      orderId: '订单号',
      payStatus: '付款状态',
      shop: 'HABA',
      img: '../../images/no_image.png',
      productInfo: '标题',
      total: '00.00',
    }],
  },

  backToHome(){
    wx.reLaunch({
      url: '../index/index',
    });
  },

  goToMenu: wxapp.handler(function* goToMenu(next, e){
    const url = e.currentTarget.dataset.url;
    wx.reLaunch({
      url,
    });

    yield next;
  }),

  goToPayment: wxapp.handler(function* goToPayment(next){
    wx.navigateTo({
      url: '../orderDetail/orderDetail',
    });

    yield next;
  }),

  goToCoupon: wxapp.handler(function* goToCoupon(next){
    wx.navigateTo({
      url: '../couponList/couponList',
    });

    yield next;
  }),

  goToDetail: wxapp.handler(function* goToDetail(next,e) {
    var orderId = e.currentTarget.dataset.id;

    wx.navigateTo({
      url: '../orderDetail/orderDetail?orderId='+orderId,
    })

    return ;

    yield next;
  }),

  cancalOrder: wxapp.handler(function* cancalOrder(next,e) {
    var id = e.currentTarget.dataset.id;
    var getOrderCancel = Api.getOrderCancel();
    var that = this;
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    wx.showModal({
      title: '订单信息',
      content: '您确定要取消订单？',
      complete: function (res) {
        if (res.confirm) {
          wx.request({
            url: getOrderCancel,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'POST',
            data: {
              order_id: id,
              token: token
            },
            complete: function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: '取消成功',
                  icon: 'success',
                  duration: 2000,
                  complete:function(){
                    setTimeout(function () {
                      wx.navigateTo({
                        url: '../me/me',
                      });
                    }, 3000);
                  }
                });

              } else {
                wx.showToast({
                  title: res.data.msg,
                  image: '../../images/error.png',
                  duration: 2000,
                });
              }
            }
          });
        }
      }
    });

    yield next;
  }),

  makeCall: wxapp.handler(function* makeCall(next){
    wx.makePhoneCall({
      phoneNumber: '13858588858',
    });

    yield next;
  }),

  // 退出登录
  logout: wxapp.handler(function* logout(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if (!token) {
      wx.reLaunch({
        url,
      });
    }
    var that = this;
    var logout = Api.logout();
    wx.request({
      url: logout,
      header: {
        'content-type':'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        token:token
      },
      complete: function (res) {
        if(res.data.status == 1){
          // 将token存入缓存
          wx.clearStorageSync();
          wx.showToast({
            title: '退出成功',
            icon: 'success',
            duration: 2000,
          });
          setTimeout(() => {
            wx.hideToast();
          that.backToHome();
        }, 3000);
        }else{
          wx.showToast({
            title: res.data.msg,
            image: '../../images/error.png',
            duration: 2000,
          });
        }
      }
    });



    yield next;
  }),

  onShow: wxapp.handler(function* onShow(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if (!token) {
      wx.reLaunch({
        url,
      });
      return ;
    }

    var that = this; 
    var getOrderList = Api.getOrderList();
    wx.request({
      url: getOrderList,
      header: {
        'content-type': 'application/json',
      },
      method: 'GET',
      data: {
        token: token
      },
      complete: function (res) {
        that.setData({ orderInfo:res.data.data});
        // console.log(that.data.orderInfo);
      }
    });

    var getCarNum = Api.getCarNum();
    // const authTokenKey = Util.authTokenKey();
    // const token = wx.getStorageSync(authTokenKey);
    wx.request({
      url: getCarNum,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({ carNum: res.data.data });
      }
    });

    yield next;
  }),

  onPullDownRefresh: wxapp.handler(function* onPullDownRefresh(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if (!token) {
      wx.reLaunch({
        url,
      });
      return;
    }

    var that = this;
    var getOrderList = Api.getOrderList();
    wx.request({
      url: getOrderList,
      header: {
        'content-type': 'application/json',
      },
      method: 'GET',
      data: {
        token: token
      },
      complete: function (res) {
        that.setData({ orderInfo: res.data.data });
        // console.log(that.data.orderInfo);
      }
    });

    var getCarNum = Api.getCarNum();
    // const authTokenKey = Util.authTokenKey();
    // const token = wx.getStorageSync(authTokenKey);
    wx.request({
      url: getCarNum,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({ carNum: res.data.data });
      }
    });
    wx.stopPullDownRefresh();  
    yield next;
  }),

  goToPay: wxapp.handler(function* goToPay(next,e) {
    var order_id = e.currentTarget.dataset.id;
    var wxPay = Api.wxPay();
    const authTokenKey = Util.authTokenKey();
    var token = wx.getStorageSync(authTokenKey);

    wx.request({
      url: wxPay,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        order_id: order_id,
        token: token
      },
      complete: function (res) {
        console.log(res);
        if (res.data.status != 0) {
          var order = res.data.data;
          if (order.nonceStr) {
            wx.requestPayment({
              timeStamp: order.timeStamp,
              nonceStr: order.nonceStr,
              package: order.package,
              signType: 'MD5',
              paySign: order.paySign,
              success: function (res) {
                wx.showToast({
                  title: "支付成功!",
                  duration: 2000,
                  complete: function () {
                    setTimeout(function () {
                      wx.navigateTo({
                        url: '../me/me',
                      });
                    }, 3000);
                  }
                });

              },
              fail: function (res) {
                wx.showToast({
                  title: res,
                  image: '../../images/error.png',
                  duration: 3000
                })
              },
              complete: function (res) {
                if (res.errMsg == 'requestPayment:ok') {
                  wx.showToast({
                    title: "支付成功!",
                    duration: 2000,
                    complete: function () {
                      setTimeout(function () {
                        wx.navigateTo({
                          url: '../me/me',
                        });
                      }, 3000);
                    }
                  });
                }
              }
            })
          } else {
            wx.showToast({
              title: '系统错误',
              image: '../../images/error.png',
              duration: 3000
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            image: '../../images/error.png',
            duration: 3000
          })
        }
      }
    });

    yield next;
  }),
  confirmOrder: wxapp.handler(function* confirmOrder(next, e) {
    var id = e.currentTarget.dataset.id;
    var confirmOrder = Api.confirmOrder();
    var that = this;
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    wx.showModal({
      title: '订单信息',
      content: '您确定要确认收货？',
      complete: function (res) {
        if (res.confirm) {
          wx.request({
            url: confirmOrder,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'POST',
            data: {
              order_id: id,
              token: token
            },
            complete: function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: '收货成功',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    setTimeout(function () {
                      wx.navigateTo({
                        url: '../me/me',
                      });
                    }, 3000);
                  }
                });

              } else {
                wx.showToast({
                  title: res.data.msg,
                  image: '../../images/error.png',
                  duration: 2000,
                });
              }
            }
          });
        }
      }
    });

    yield next;
  })

});
